/**
 * 比对路由权限
 *
 * @param {Array} userRouter 后台返回的路由权限json
 * @param {Array} allRouter 前端配置好的路由权限数据
 * @return {Array} realRoutes 过滤之后的符合条件的路由
 */

export function recursionRouter(userRouter = [], allRouter = []) {
    var realRoutes = [];
    allRouter.forEach(v => {
        userRouter.forEach(item => {
            if (item.name === v.name) {
                if (item.children && item.children.length > 0) {
                    v.children = recursionRouter(item.children, v.children);
                }
                realRoutes.push(v)
            }
        })
    })
    return realRoutes;
}
/**
* 指定返回的默认路由
*/
export function setDefaultRoute(routes) {
    routes.forEach((v, i) => {
        if (v.children && v.children.length > 0) {
            v.redirect = { name: v.children[0].name }
            setDefaultRoute(v.children);
        }
    })
}

/**
* 将扁平化的路由改为树形结构
*/
export const nestRouter = (menu, item) => {
    let fatherPath = item.path.split('/')
    fatherPath.pop()
    fatherPath = fatherPath.join('/')
    const recursion = (menu) => {
        for (let i = menu.length - 1; i >= 0; i--) {
            if (menu[i].path === fatherPath) {
                return menu[i].children.push(item)
            }
            if (menu[i].children && menu[i].children.length !== 0) recursion(menu[i].children)
        }
    }
    recursion(menu)
    return menu
}
/**
* 路由数组递归扁平化
*/
export const flattenArray = (arr) => {
    let result = [];
    arr.forEach(item => {
        if (item.children && Array.isArray(item.children)) {
            result.push({ ...item, children: [] });
            result = result.concat(flattenArray(item.children));
        } else {
            result.push(item);
        }
    });
    return result;
}